import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sinosheets/utils/language/lang_model.dart';
import 'package:sinosheets/utils/favorite/flash_sale_product_model.dart';
import 'package:sinosheets/utils/favorite/normal_product_model.dart';
import 'dart:async';

class IsarManager {
  static final IsarManager _instance = IsarManager._internal();
  factory IsarManager() => _instance;

  Isar? _isar;
  bool _isInitialized = false;

  IsarManager._internal();

  /// 初始化Isar数据库
  Future<void> init() async {
    // 如果已经初始化，直接返回
    if (_isInitialized && _isar != null) {
      return;
    }

    try {
      print('IsarManager: 开始初始化Isar数据库');
      final dir = await getApplicationDocumentsDirectory();
      print('IsarManager: 数据库目录: ${dir.path}');

      // 合并所有Schema
      final schemas = [
        LangModelSchema,
        FlashSaleProductModelSchema,
        NormalProductModelSchema,
      ];

      print('IsarManager: 注册的Schema数量: ${schemas.length}');

      _isar = await Isar.open(
        schemas,
        directory: dir.path,
      );

      _isInitialized = true;
      print('IsarManager: Isar数据库初始化成功');
    } catch (e) {
      print('IsarManager: 初始化Isar失败: $e');
      print('IsarManager: 错误类型: ${e.runtimeType}');

      // 如果Isar已经打开，直接获取实例
      if (e.toString().contains('Instance has already been opened')) {
        try {
          _isar = Isar.getInstance();
          _isInitialized = true;
          print('IsarManager: 获取现有Isar实例成功');
        } catch (e2) {
          print('IsarManager: 获取Isar实例失败: $e2');
          rethrow;
        }
      } else {
        rethrow;
      }
    }
  }

  /// 获取Isar实例
  Isar get isar {
    if (!_isInitialized || _isar == null) {
      throw Exception('IsarManager未初始化，请先调用init()方法');
    }
    return _isar!;
  }

  /// 检查是否已初始化
  bool get isInitialized => _isInitialized;

  /// 关闭数据库连接
  Future<void> close() async {
    if (_isar != null && _isInitialized) {
      await _isar!.close();
      _isar = null;
      _isInitialized = false;
      print('IsarManager: 数据库连接已关闭');
    }
  }
}
